package com.newmodelclient.baselib.notify;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * 作者：sean
 * 创建时间：2017/6/23 10:57
 * 功能说明：用于管理RxBus的事件和Rxjava相关代码的生命周期处理
 */

public class RxManager {

    public RxBus mRxBus = RxBus.$();
    private Map<String, Observable<?>> mObservables = new HashMap<>();// 管理观察者
//    private CompositeSubscription mCompositeSubscription = new CompositeSubscription();// 管理订阅者者
    private CompositeDisposable composite2 = new CompositeDisposable();

    private static RxManager rxManager;

    public void on(String eventName, Consumer<Object> action1) {
        Observable<?> mObservable = mRxBus.register(eventName);
        mObservables.put(eventName, mObservable);
        composite2.add(mObservable.subscribe(action1, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {
                throwable.printStackTrace();
            }
        }));
//        mCompositeSubscription.add(mObservable.observeOn(AndroidSchedulers.mainThread())
//                .subscribe(action1, new Action1<Throwable>() {
//                    @Override
//                    public void call(Throwable throwable) {
//                        throwable.printStackTrace();
//                    }
//                }));
    }

    public void add(Disposable disposable) {
        composite2.add(disposable);
//        mCompositeSubscription.add(m);
    }

    public void clear() {
        composite2.dispose();
//        mCompositeSubscription.unsubscribe();// 取消订阅
        for (Map.Entry<String, Observable<?>> entry : mObservables.entrySet()) {
            mRxBus.unregister(entry.getKey(), entry.getValue());// 移除观察
        }
    }

    public void post(Object tag, Object content) {
        mRxBus.post(tag, content);
    }


    public static RxManager getInstance() {
        if (rxManager == null) {
            rxManager = new RxManager();
        }
        return rxManager;
    }
}
